package com.puer.config;

import com.puer.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Autowired
    private TokenInterceptor tokenInterceptor;
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 对所有路径进行跨域配置
                .allowedOrigins("*")    // 允许所有来源访问
                .allowedHeaders("*")    // 允许所有请求头
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); // 允许的请求方法
    }

    @Value("${file-save-path}")
    private String fileSavePath;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * 配置资源映射
         * 如果访问的资源路径是以“/images/”开头的，
         * 就映射至本机的“D:/实训/普洱学院/实训/2025-10-24/images”这个文件夹内，去找你要的资源
         * 注意：”D:/实训/普洱学院/实训/2025-10-24/images“后面的“/”一定要带上
         */
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + fileSavePath + "/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/favicon.ioc").addResourceLocations("classpath:/META-INF/resources/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login", "/user/register", "/swagger-resources/**", "/doc.html", "/webjars/**",
                        "/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**", "/favicon.ico", "/error", "/images/**");
    }
}